//
//  MLUserAccountTool.swift
//  MLSina20160624
//
//  Created by manmanlang on 16/6/27.
//  Copyright © 2016年 manmanlang. All rights reserved.
//

import UIKit

//保存的路径
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")

class MLUserAccountTool: NSObject {
    
    static let sharedTool:MLUserAccountTool = MLUserAccountTool()
    ///保存对象
    func saveUserAccount(userAccount: MLUserAccount){
        //第一次调用单例为nil 需要提前为单例对象赋值
        self.userAccount = userAccount
        
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
    }
    ///获取对象
    func getUserAccount() ->MLUserAccount?{
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? MLUserAccount
        return result
    }
    //保存的用户数据
    var userAccount: MLUserAccount?
    
    //是否登录
    var isLogin:Bool {
        //如果access_token 为nil 就代表没有登录
        return accessToken != nil
    }
    
    //令牌－访问（只读属性）
    var accessToken: String? {
        if userAccount?.access_token == nil {
            return nil
        }else {
            //expires_Date(微博返回时间)和当前时间比较是降序 代表没有过期 代表正在过期中....QAQ
            if userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return userAccount?.access_token
            }else {
                return nil
            }
        }
    }
    
    override init() {
        //需要先初始化对象 否则无法调用getUserAccount方法
        super.init()
        userAccount = getUserAccount()
    }
}
